#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    File Name:      security_utils
    Author:         'daze'
    date:           2018/11/16
"""
import binascii
from Crypto import Random
from Crypto.Cipher import AES

from AutoWool.main.utils.log_utils import Log


def bytes2hex(bytes_content) -> str:
    # return binascii.b2a_hex(bytes_content)  # 返回二进制数据的十六进制表示(是bytes)
    return bytes_content.hex()


def hex2bytes(hex_content) -> bytes:
    # return binascii.a2b_hex(hex_content)  # 从十六进制字符串hexstr返回二进制数据
    return bytes.fromhex(hex_content)


class SecurityUtils:
    key = '1234567890!@#$%^'  # 秘钥，必须是16、24或32字节长度
    iv = Random.new().read(16)  # 随机向量，必须是16字节长度，注意这要是直接写到程序中则下次的 random 数额就不一样了，导致没法解密，所以这里直接写死了
    iv = binascii.a2b_hex('e1e8e4f230a56052c5903ed11e0b5501')

    @staticmethod
    def _encode2bytes(msg: str) -> bytes:
        Log.log('iv=' + str(binascii.b2a_hex(SecurityUtils.iv)))
        cipher1 = AES.new(SecurityUtils.key, AES.MODE_CFB, SecurityUtils.iv)  # 密文生成器,MODE_CFB为加密模式
        encrypt_msg = SecurityUtils.iv + cipher1.encrypt(msg)
        # hex_encrypt_str = str(binascii.b2a_hex(encrypt_msg))  # b2a_hex 将二进制密文转换为16机制显示
        # Log.log("SecurityUtils 加密后的值16进制为:" + hex_encrypt_str)
        return encrypt_msg

    @staticmethod
    def encode2hex(msg: str) -> str:
        return bytes2hex(SecurityUtils._encode2bytes(msg))

    @staticmethod
    def _decode_bytes(encoded_msg: bytes) -> str:
        cipher2 = AES.new(SecurityUtils.key, AES.MODE_CFB, SecurityUtils.iv)  # 解密时必须重新创建新的密文生成器
        decrypt_msg = cipher2.decrypt(encoded_msg[16:])  # 后十六位是真正的密文
        return decrypt_msg.decode('utf-8')

    @staticmethod
    def decode_hex(encoded_hex_msg: str) -> str:
        return SecurityUtils._decode_bytes(hex2bytes(encoded_hex_msg))
